/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package CONTROLEUR;

import CONTROLEUR.exceptions.IllegalOrphanException;
import CONTROLEUR.exceptions.NonexistentEntityException;
import CONTROLEUR.exceptions.PreexistingEntityException;
import MODEL.Prospect;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import MODEL.Reserver;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author ahmed
 */
public class ProspectJpaController implements Serializable {

    public ProspectJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Prospect prospect) throws PreexistingEntityException, Exception {
        if (prospect.getReserverCollection() == null) {
            prospect.setReserverCollection(new ArrayList<Reserver>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Reserver> attachedReserverCollection = new ArrayList<Reserver>();
            for (Reserver reserverCollectionReserverToAttach : prospect.getReserverCollection()) {
                reserverCollectionReserverToAttach = em.getReference(reserverCollectionReserverToAttach.getClass(), reserverCollectionReserverToAttach.getReserverPK());
                attachedReserverCollection.add(reserverCollectionReserverToAttach);
            }
            prospect.setReserverCollection(attachedReserverCollection);
            em.persist(prospect);
            for (Reserver reserverCollectionReserver : prospect.getReserverCollection()) {
                Prospect oldProspectOfReserverCollectionReserver = reserverCollectionReserver.getProspect();
                reserverCollectionReserver.setProspect(prospect);
                reserverCollectionReserver = em.merge(reserverCollectionReserver);
                if (oldProspectOfReserverCollectionReserver != null) {
                    oldProspectOfReserverCollectionReserver.getReserverCollection().remove(reserverCollectionReserver);
                    oldProspectOfReserverCollectionReserver = em.merge(oldProspectOfReserverCollectionReserver);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findProspect(prospect.getIdPro()) != null) {
                throw new PreexistingEntityException("Prospect " + prospect + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Prospect prospect) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Prospect persistentProspect = em.find(Prospect.class, prospect.getIdPro());
            Collection<Reserver> reserverCollectionOld = persistentProspect.getReserverCollection();
            Collection<Reserver> reserverCollectionNew = prospect.getReserverCollection();
            List<String> illegalOrphanMessages = null;
            for (Reserver reserverCollectionOldReserver : reserverCollectionOld) {
                if (!reserverCollectionNew.contains(reserverCollectionOldReserver)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Reserver " + reserverCollectionOldReserver + " since its prospect field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Reserver> attachedReserverCollectionNew = new ArrayList<Reserver>();
            for (Reserver reserverCollectionNewReserverToAttach : reserverCollectionNew) {
                reserverCollectionNewReserverToAttach = em.getReference(reserverCollectionNewReserverToAttach.getClass(), reserverCollectionNewReserverToAttach.getReserverPK());
                attachedReserverCollectionNew.add(reserverCollectionNewReserverToAttach);
            }
            reserverCollectionNew = attachedReserverCollectionNew;
            prospect.setReserverCollection(reserverCollectionNew);
            prospect = em.merge(prospect);
            for (Reserver reserverCollectionNewReserver : reserverCollectionNew) {
                if (!reserverCollectionOld.contains(reserverCollectionNewReserver)) {
                    Prospect oldProspectOfReserverCollectionNewReserver = reserverCollectionNewReserver.getProspect();
                    reserverCollectionNewReserver.setProspect(prospect);
                    reserverCollectionNewReserver = em.merge(reserverCollectionNewReserver);
                    if (oldProspectOfReserverCollectionNewReserver != null && !oldProspectOfReserverCollectionNewReserver.equals(prospect)) {
                        oldProspectOfReserverCollectionNewReserver.getReserverCollection().remove(reserverCollectionNewReserver);
                        oldProspectOfReserverCollectionNewReserver = em.merge(oldProspectOfReserverCollectionNewReserver);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                BigDecimal id = prospect.getIdPro();
                if (findProspect(id) == null) {
                    throw new NonexistentEntityException("The prospect with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(BigDecimal id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Prospect prospect;
            try {
                prospect = em.getReference(Prospect.class, id);
                prospect.getIdPro();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The prospect with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Reserver> reserverCollectionOrphanCheck = prospect.getReserverCollection();
            for (Reserver reserverCollectionOrphanCheckReserver : reserverCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Prospect (" + prospect + ") cannot be destroyed since the Reserver " + reserverCollectionOrphanCheckReserver + " in its reserverCollection field has a non-nullable prospect field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(prospect);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Prospect> findProspectEntities() {
        return findProspectEntities(true, -1, -1);
    }

    public List<Prospect> findProspectEntities(int maxResults, int firstResult) {
        return findProspectEntities(false, maxResults, firstResult);
    }

    private List<Prospect> findProspectEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Prospect.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Prospect findProspect(BigDecimal id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Prospect.class, id);
        } finally {
            em.close();
        }
    }

    public int getProspectCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Prospect> rt = cq.from(Prospect.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
